#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include "common.h"

#define PATH "."
#define FILE_NAME "fifo"
#define DEFAULT_MODE 0666

class Pipe
{
public:
    // 构造函数用于创建管道
    Pipe(const std::string &path, const std::string &name) : _path(path), _name(name)
    {
        _path_name = path + "/" + name;
        // 创建管道文件
        umask(0);
        int n = mkfifo(_path_name.c_str(), DEFAULT_MODE);
        if (n < 0)
        {
            ERR_EXIT("Pipe");
        }
    }
    // 析构函数用于删除管道文件
    ~Pipe()
    {
        int n = unlink(_path_name.c_str());
        if (n < 0)
        {
            ERR_EXIT("unlink");
        }
        std::cout << "~Pipe：unlink success" << std::endl;
    }

private:
    std::string _path = "."; // 不写路径默认当前路径
    std::string _name = "default_fifo";
    std::string _path_name = _path + "/" + _name;
};

class PipeOper
{
public:
    PipeOper(const std::string &path, const std::string &name):_path(path),_name(name),_fd(-1)
    {
         _path_name = _path + "/" + _name;
    }
    int OpenForRead()
    {
        _fd = open(_path_name.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("OpenForRead");
        }
        std::cout << "OpenForRead: open success" << std::endl;
        return _fd;
    }
    int OpenForWrite()
    {
        _fd = open(_path_name.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("OpenForWrite");
        }
        std::cout << "OpenForWrite: open success" << std::endl;
        return _fd;
    }
    bool Wait()
    {
        char ch;
        if(size_t flag = read(_fd, &ch,1))
        {
            std::cout<<"唤醒成功！"<<std::endl;
            return true;
        }
        else
        {
            return false;
        }
    }
    void WakeUp()
    {
        char ch = 'w';
        int flag = write(_fd,&ch,1);
        std::cout<<"尝试唤醒"<<std::endl;
    }
    void Close()
    {
        close(_fd);
        std::cout << "close success" << std::endl;
        ;
    }

private:
    int _fd;
    std::string _path;
    std::string _name;
    std::string _path_name;

};